package gulimall.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 解决feign远程调用请求头丢失问题
 *
 * @author HLF
 * @date 2022/9/1 21:00
 */
@Configuration
public class GulimallFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            System.out.println("RequestInterceptor线程id："+Thread.currentThread().getId());

            //RequestContextHolder可以拿到刚进来的这个请求数据，也即调用我们controller下的请求方法当时的一些请求头信息
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                //获取到当前请求的对象，也即老请求
                HttpServletRequest request = requestAttributes.getRequest();
                //把获取到的请求对象的头信息都同步进来,主要同步cookie，
                String cookie = request.getHeader("Cookie");
                //给新请求同步了老请求的头信息，这样最终远程调用的时候，
                template.header("Cookie", cookie);
                System.out.println("feign远程之前先进行RequestInterceptor.apply()");
            }
        };
    }
}
